package com.vue.cn.controller;

import com.vue.cn.common.http.AjaxResult;
import com.vue.cn.common.http.StatusEnum;
import com.vue.cn.domin.Employee;
import com.vue.cn.service.EmployeeService;
import com.vue.cn.utils.mail.MailUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ActiveController {
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private MailUtils mailUtils;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @PutMapping("active")
    @ResponseBody
    public AjaxResult active(String email) throws MessagingException, IOException, TemplateException {
        Employee byEmail = employeeService.findByEmail(email);
        if (byEmail == null) {
            return AjaxResult.error(StatusEnum.EEEOR_ACTIVE);
        }
        if (byEmail.getActive()) {
            return AjaxResult.ok("账号已处于激活状态");
        }

        //激活页面的模板设置
        Map<String, String> map = new HashMap<>();
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Template template = configuration.getTemplate("active.ftl", "utf-8");
        map.put("activeUrl", "http://localhost:8080/active/" + byEmail.getEmployeeId());
        map.put("employeeName", byEmail.getEmployeeName());
        StringWriter write = new StringWriter();
        template.process(map, write);

        //发送激活页面到邮箱
        mailUtils.sendActive(email,write.toString());
        write.close();

        return AjaxResult.ok("邮箱激活已发送");
    }


    @GetMapping("active/{id}")
    public String active(@PathVariable int id) {
        Employee byEmail = employeeService.findById(id);

        byEmail.setActive(true);
        int row = employeeService.edit(byEmail);
        if (row > 0) {
            return "redirect:http://localhost:63343/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B/login.html";
        }
        return "OK";

    }
}
